package com.chen.blue.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Created By CLT On 2023/10/24.
 */
@SuppressWarnings("all")
@Component
public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextAware {

    /**
     * 使用spring生命周期获取上下文内容解决不再spring环境中获取不到bean的问题
     */
    private static ConfigurableListableBeanFactory factory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        this.factory = configurableListableBeanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 根据类型获取bean
     *
     * @param clzz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clzz) {
        T bean = (T) factory.getBean(clzz);
        return bean;
    }

    /**
     * 根据bean名称获取bean
     *
     * @param beanName
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        T bean = (T) factory.getBean(beanName);
        return bean;
    }

    /**
     * 返回spring上下文
     *
     * @return
     */
    public static Environment getEnvironment() {
        return applicationContext.getEnvironment();
    }

    /**
     * 返回环境属性
     *
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        return getEnvironment().getProperty(key);
    }

}
